﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.RobotJog.Controls.CUiJointsControl
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using DnProcessSimulateCommands.RobotJog.Controls.Joints;
using EngineeringInternalExtension;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Forms;
using System.Windows.Markup;
using System.Windows.Media;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.Ui;
using UiInternalControls.WPF.JointJogControls;


namespace DnProcessSimulateCommands.RobotJog.Controls;

public class CUiJointsControl : System.Windows.Controls.UserControl, IComponentConnector
{
  private JointsLayout _layout;
  private CApRJRobotJogJointsLogic m_jointJogApplication;
  private bool m_ShowDependentJoints;
  private JointsLayoutBuilder _jointsLayoutBuilder;
  private AllJointsLayoutBuilder _allJointsLayoutBuilder;
  private ExternalJointsLayoutBuilder _externalJointsLayoutBuilder;
  private List<ColumnDefinition> _jointsGridAllColumns;
  private TxObject_DeletedEventHandler _actionExtAxisDeletedEventHandler;
  internal Grid jointsGrid;
  internal ColumnDefinition Joint;
  internal ColumnDefinition SteeringPoses;
  internal ColumnDefinition Value;
  internal ColumnDefinition Percentage;
  internal ColumnDefinition LowerLimit;
  internal ColumnDefinition UpperLimit;
  internal System.Windows.Controls.Image btnLowLimit_img;
  internal System.Windows.Controls.Image btnUpLimit_img;
  internal Popup tooltip;
  internal TextBlock tooltipTextBlock;
  private bool _contentLoaded;

  public JointsLayout Layout
  {
    get => this._layout;
    set
    {
      if (value == this._layout)
        return;
      this._layout = value;
      this.SetLayout(this._layout);
    }
  }

  public string RawColumnData { get; set; }

  public bool ShowDependentJoints
  {
    get => this.m_ShowDependentJoints;
    set
    {
      this.m_jointJogApplication.ShowDependentJoints(value);
      this.m_ShowDependentJoints = value;
    }
  }

  public int JointsCount => this._jointsLayoutBuilder.JointsCountInGrid();

  public CUiJointsControl()
  {
    this.InitializeComponent();
    this.btnLowLimit_img.Source = TxImageManager.GetImageByKey(nameof (LowerLimit)).ConvertTo<ImageSource>(new System.Drawing.Size());
    this.btnUpLimit_img.Source = TxImageManager.GetImageByKey(nameof (UpperLimit)).ConvertTo<ImageSource>(new System.Drawing.Size());
  }

  public void InitializeControl(CApRJRobotJogJointsLogic jointJogApplication)
  {
    this.m_jointJogApplication = jointJogApplication;
    this._allJointsLayoutBuilder = new AllJointsLayoutBuilder(this, this.m_jointJogApplication);
    this._externalJointsLayoutBuilder = new ExternalJointsLayoutBuilder(this, this.m_jointJogApplication);
    if (this._jointsGridAllColumns == null)
      this._jointsGridAllColumns = this.jointsGrid.ColumnDefinitions.ToList<ColumnDefinition>();
    this.Layout = JointsLayout.ExternalJoints;
  }

  public void UnInitializeControl()
  {
    if (this.m_jointJogApplication == null)
      return;
    this.m_jointJogApplication.DisposeNodeData();
  }

  public void RegisterForExternalAxisDeleted(TxObject_DeletedEventHandler objectDeleted)
  {
    if (objectDeleted == null)
      return;
    this._actionExtAxisDeletedEventHandler = objectDeleted;
    this.RegisterForExternalAxisDeleted((this.m_jointJogApplication.RootDevice as TxRobot).ExternalAxes);
  }

  public void UnRegisterForExternalAxisDeleted()
  {
    this.UnRegisterForExternalAxisDeleted((this.m_jointJogApplication.RootDevice as TxRobot).ExternalAxes);
  }

  private void RegisterForExternalAxisDeleted(TxObjectList externalAxisList)
  {
    foreach (TxJoint externalAxis in (Collection<ITxObject>) externalAxisList)
      externalAxis.Deleted += this._actionExtAxisDeletedEventHandler;
  }

  private void UnRegisterForExternalAxisDeleted(TxObjectList externalAxisList)
  {
    foreach (TxJoint externalAxis in (Collection<ITxObject>) externalAxisList)
      externalAxis.Deleted -= this._actionExtAxisDeletedEventHandler;
  }

  public void RegisterForExternalAxisesChange()
  {
    (this.m_jointJogApplication.RootDevice as TxRobot).ExternalAxisAdded += new TxRobot_ExternalAxisAddedEventHandler(this.Robot_OnExternalAxisesListChanged);
    (this.m_jointJogApplication.RootDevice as TxRobot).ExternalAxisRemoved += new TxRobot_ExternalAxisRemovedEventHandler(this.Robot_OnExternalAxisesListChanged);
  }

  public void UnRegisterForExternalAxisesChange()
  {
    (this.m_jointJogApplication.RootDevice as TxRobot).ExternalAxisAdded -= new TxRobot_ExternalAxisAddedEventHandler(this.Robot_OnExternalAxisesListChanged);
    (this.m_jointJogApplication.RootDevice as TxRobot).ExternalAxisRemoved -= new TxRobot_ExternalAxisRemovedEventHandler(this.Robot_OnExternalAxisesListChanged);
  }

  private void Robot_OnExternalAxisesListChanged(object sender, EventArgs args)
  {
    if (this._actionExtAxisDeletedEventHandler != null)
    {
      TxObjectList extertnalAxisesList = new TxObjectList();
      this.m_jointJogApplication.ExecuteOnJointsNodesData((Action<CUiJointNodeData>) (x =>
      {
        if (!x.IsExternalJoint)
          return;
        ((Collection<ITxObject>) extertnalAxisesList).Add((ITxObject) x.Joint);
      }));
      this.UnRegisterForExternalAxisDeleted(extertnalAxisesList);
    }
    this.RefreshJoints();
    if (this._actionExtAxisDeletedEventHandler == null)
      return;
    this.RegisterForExternalAxisDeleted((this.m_jointJogApplication.RootDevice as TxRobot).ExternalAxes);
  }

  private void jointsGrid_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
  {
    bool flag = false;
    if (this.Layout == JointsLayout.AllJoints && e.Source is FrameworkElement element && element.IsDescendantOf((DependencyObject) this.jointsGrid))
    {
      while (element.Parent != this.jointsGrid && element.Parent != null)
        element = element.Parent as FrameworkElement;
      int column = Grid.GetColumn((UIElement) element);
      int row = Grid.GetRow((UIElement) element);
      if (column == this.jointsGrid.ColumnDefinitions.IndexOf(this.Joint))
      {
        CUiJointNodeData joinData = this._allJointsLayoutBuilder.GetJoinData(row);
        if (joinData != null)
        {
          string textToFormat = joinData.TooltipText;
          if (!string.IsNullOrEmpty(textToFormat))
          {
            flag = true;
            if (!this.tooltip.IsOpen)
              this.tooltip.IsOpen = true;
            System.Windows.Point position = e.GetPosition((IInputElement) this.jointsGrid);
            this.tooltip.HorizontalOffset = position.X + 20.0;
            this.tooltip.VerticalOffset = position.Y;
            int num1 = (int) new FormattedText(textToFormat, CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight, new Typeface(this.tooltipTextBlock.FontFamily, this.tooltipTextBlock.FontStyle, this.tooltipTextBlock.FontWeight, this.tooltipTextBlock.FontStretch), this.tooltipTextBlock.FontSize, (System.Windows.Media.Brush) System.Windows.Media.Brushes.Black).Width / (int) (SystemParameters.VirtualScreenWidth / 2.0);
            int num2 = textToFormat.Length / (num1 + 1);
            if (num1 > 0)
            {
              for (int index = 0; index < num1; ++index)
                textToFormat = textToFormat.Insert((index + 1) * num2, Environment.NewLine);
            }
            this.tooltipTextBlock.Text = textToFormat;
          }
        }
      }
    }
    if (!this.tooltip.IsOpen || flag)
      return;
    this.tooltip.IsOpen = false;
  }

  private void jointsGrid_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
  {
    if (!this.tooltip.IsOpen)
      return;
    this.tooltip.IsOpen = false;
  }

  public void Reset() => this.m_jointJogApplication.Reset();

  public bool CheckForOutOfLimitsJoints()
  {
    bool flag = false;
    if (TxApplication.Options.Motion.LimitsCheck && this.m_jointJogApplication.AreOutOfLimitsJoints())
    {
      if (CApRJRobotJogNotificationService.Notify(string.Format(RJRobotJogResources.OUT_OF_LIMITS_JOINTS_MESSAGE, (object) ((ITxObject) this.m_jointJogApplication.RootDevice).Name), RJRobotJogResources.RobotJogName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
      {
        this.m_jointJogApplication.TrimOutOfLimitsJoints();
        flag = true;
      }
    }
    else
      flag = true;
    return flag;
  }

  public void RefreshJoints()
  {
    this.ApplyColumnsData(CUiRJJointsOptionsForm.DeSerializeColumns(this.RawColumnData));
    this.ClearGrid();
    this._jointsLayoutBuilder.InitGrid();
    this.m_jointJogApplication.DisposeNodeData();
    this.m_jointJogApplication.ClearNodeData();
    this.m_jointJogApplication.ClearExternalDevices();
    this.AddNodeData((CUiNodeData) this.m_jointJogApplication.GetDeviceNodeData(this.m_jointJogApplication.RootDevice));
    this.m_jointJogApplication.SetOldExternalDevicesValues();
    this._jointsLayoutBuilder.AditionalGridInit();
    this.InitSliders();
  }

  private void InitSliders()
  {
    double? prismaticStepSizeValue;
    double? revoluteStepSizeValue;
    int? sliderSensitivityValue;
    CUiRJJointsOptionsForm.LoadOptionsDataByWindowType(out prismaticStepSizeValue, out revoluteStepSizeValue, out sliderSensitivityValue);
    if (!prismaticStepSizeValue.HasValue || !revoluteStepSizeValue.HasValue || !sliderSensitivityValue.HasValue)
      return;
    this.m_jointJogApplication.FireOptionsChanged((object) this, prismaticStepSizeValue.Value, revoluteStepSizeValue.Value, sliderSensitivityValue.Value);
  }

  private void SetLayout(JointsLayout layout)
  {
    switch (layout)
    {
      case JointsLayout.AllJoints:
        this._jointsLayoutBuilder = (JointsLayoutBuilder) this._allJointsLayoutBuilder;
        break;
      case JointsLayout.ExternalJoints:
        this._jointsLayoutBuilder = (JointsLayoutBuilder) this._externalJointsLayoutBuilder;
        break;
    }
    this.RefreshJoints();
  }

  private void ClearGrid()
  {
    this.jointsGrid.RowDefinitions.Clear();
    foreach (UIElement element in this.jointsGrid.Children.Cast<UIElement>().Where<UIElement>((Func<UIElement, bool>) (x => x is Border)).ToList<UIElement>())
      this.jointsGrid.Children.Remove(element);
  }

  internal void AddRowToGrid(
    CUiJointNodeData jointData,
    Border jointNameBorder,
    Border sliderBorder,
    Border valueBorder,
    Border percentageBorder,
    Border lowSoftLimitBorder,
    Border upperSoftLimitBorder)
  {
    RowDefinition rowDefinition = new RowDefinition()
    {
      Height = new GridLength(24.0)
    };
    this.jointsGrid.RowDefinitions.Add(rowDefinition);
    int num = this.jointsGrid.RowDefinitions.Count - 1;
    foreach (ColumnDefinition columnDefinition in (IEnumerable<ColumnDefinition>) this.jointsGrid.ColumnDefinitions)
    {
      if (columnDefinition == this.Joint && jointNameBorder != null)
      {
        Grid.SetColumn((UIElement) jointNameBorder, this.jointsGrid.ColumnDefinitions.IndexOf(this.Joint));
        Grid.SetRow((UIElement) jointNameBorder, num);
        this.jointsGrid.Children.Add((UIElement) jointNameBorder);
      }
      else if (columnDefinition == this.Value && valueBorder != null)
      {
        Grid.SetColumn((UIElement) valueBorder, this.jointsGrid.ColumnDefinitions.IndexOf(this.Value));
        Grid.SetRow((UIElement) valueBorder, num);
        this.jointsGrid.Children.Add((UIElement) valueBorder);
      }
      else if (columnDefinition == this.SteeringPoses && sliderBorder != null)
      {
        Grid.SetColumn((UIElement) sliderBorder, this.jointsGrid.ColumnDefinitions.IndexOf(this.SteeringPoses));
        Grid.SetRow((UIElement) sliderBorder, num);
        this.jointsGrid.Children.Add((UIElement) sliderBorder);
      }
      else if (columnDefinition == this.Percentage && percentageBorder != null)
      {
        Grid.SetColumn((UIElement) percentageBorder, this.jointsGrid.ColumnDefinitions.IndexOf(this.Percentage));
        Grid.SetRow((UIElement) percentageBorder, num);
        this.jointsGrid.Children.Add((UIElement) percentageBorder);
      }
      else if (columnDefinition == this.LowerLimit && lowSoftLimitBorder != null)
      {
        Grid.SetColumn((UIElement) lowSoftLimitBorder, this.jointsGrid.ColumnDefinitions.IndexOf(this.LowerLimit));
        Grid.SetRow((UIElement) lowSoftLimitBorder, num);
        this.jointsGrid.Children.Add((UIElement) lowSoftLimitBorder);
      }
      else if (columnDefinition == this.UpperLimit && upperSoftLimitBorder != null)
      {
        Grid.SetColumn((UIElement) upperSoftLimitBorder, this.jointsGrid.ColumnDefinitions.IndexOf(this.UpperLimit));
        Grid.SetRow((UIElement) upperSoftLimitBorder, num);
        this.jointsGrid.Children.Add((UIElement) upperSoftLimitBorder);
      }
    }
    if (jointData == null)
      return;
    jointData.GridRow = rowDefinition;
  }

  private void AddNodeData(CUiNodeData nodeData)
  {
    CUiJointNodeData jointData = nodeData as CUiJointNodeData;
    CUiDeviceNodeData cuiDeviceNodeData = nodeData as CUiDeviceNodeData;
    CUiComponentNodeData componentNodeData = nodeData as CUiComponentNodeData;
    if (jointData != null)
    {
      jointData.JointValue = jointData.Joint.CurrentValue;
      this._jointsLayoutBuilder.AddJointToGrid(jointData);
    }
    else if (cuiDeviceNodeData != null)
    {
      TxComponentStructureTypeEnum componentStructureType = TxEngineeringDataInternal.GetComponentStructureType((ITxObject) cuiDeviceNodeData.Device);
      foreach (CUiNodeData childrenNode in cuiDeviceNodeData.ChildrenNodes)
      {
        if (componentStructureType != null)
          this.AddNodeData(childrenNode);
        else if (childrenNode is CUiJointNodeData)
          this.AddNodeData(childrenNode);
      }
    }
    else
    {
      if (componentNodeData == null)
        return;
      TxComponentStructureTypeEnum componentStructureType = TxEngineeringDataInternal.GetComponentStructureType((ITxObject) componentNodeData.NodeObject);
      foreach (CUiNodeData childrenNode in componentNodeData.ChildrenNodes)
      {
        if (componentStructureType != null)
          this.AddNodeData(childrenNode);
        else if (childrenNode is CUiJointNodeData)
          this.AddNodeData(childrenNode);
      }
    }
  }

  public void ApplyColumnsData(List<CUiRJJointsColumnData> columnsData)
  {
    this.ReorderColumns(columnsData);
    this.SetColumnsVisibility(columnsData);
    this.RawColumnData = CUiRJJointsOptionsForm.SerializeColumns(columnsData);
  }

  private void ReorderColumns(List<CUiRJJointsColumnData> columnsData)
  {
    List<string> listOrder = new List<string>();
    listOrder.Add(ColumnsIDS.Joint);
    foreach (CUiRJJointsColumnData jointsColumnData in columnsData)
    {
      if (jointsColumnData.ColumnName == ColumnsIDS.Value)
      {
        listOrder.Add(ColumnsIDS.Steering);
        listOrder.Add(ColumnsIDS.Value);
      }
      else
        listOrder.Add(jointsColumnData.ColumnName);
    }
    this.jointsGrid.ColumnDefinitions.Clear();
    foreach (ColumnDefinition jointsGridAllColumn in this._jointsGridAllColumns)
      this.jointsGrid.ColumnDefinitions.Add(jointsGridAllColumn);
    this.jointsGrid.ReorderColumns(listOrder);
    this._jointsGridAllColumns.Clear();
    foreach (ColumnDefinition columnDefinition in (IEnumerable<ColumnDefinition>) this.jointsGrid.ColumnDefinitions)
      this._jointsGridAllColumns.Add(columnDefinition);
  }

  private void SetColumnsVisibility(List<CUiRJJointsColumnData> columnsData)
  {
    foreach (CUiRJJointsColumnData jointsColumnData in columnsData)
    {
      CUiRJJointsColumnData columnData = jointsColumnData;
      if (!columnData.Visible)
      {
        if (columnData.ColumnName == ColumnsIDS.Value)
        {
          ColumnDefinition column1 = this.jointsGrid.ColumnDefinitions.First<ColumnDefinition>((Func<ColumnDefinition, bool>) (Col => Col.Name == ColumnsIDS.Steering));
          this.jointsGrid.ColumnDefinitions.RemoveAt(column1.Index() - 1);
          this.jointsGrid.ColumnDefinitions.Remove(column1);
          ColumnDefinition column2 = this.jointsGrid.ColumnDefinitions.First<ColumnDefinition>((Func<ColumnDefinition, bool>) (Col => Col.Name == columnData.ColumnName));
          this.jointsGrid.ColumnDefinitions.RemoveAt(column2.Index() - 1);
          this.jointsGrid.ColumnDefinitions.Remove(column2);
        }
        else
        {
          ColumnDefinition column = this.jointsGrid.ColumnDefinitions.First<ColumnDefinition>((Func<ColumnDefinition, bool>) (Col => Col.Name == columnData.ColumnName));
          this.jointsGrid.ColumnDefinitions.RemoveAt(column.Index() - 1);
          this.jointsGrid.ColumnDefinitions.Remove(column);
        }
      }
    }
  }

  public void ResetToHardLimit(TxKinematicJointLimits limitControl)
  {
    CUiJointNodeData joinData = this._jointsLayoutBuilder.GetJoinData((FrameworkElement) limitControl);
    if ((bool) ((FrameworkElement) limitControl).Tag)
      joinData.ResetToUpperHardLimits();
    else
      joinData.ResetToLowerHardLimits();
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  public void InitializeComponent()
  {
    if (this._contentLoaded)
      return;
    this._contentLoaded = true;
    System.Windows.Application.LoadComponent((object) this, new Uri("/DnProcessSimulateCommands;component/robotjog/controls/joints/cuijointscontrol.xaml", UriKind.Relative));
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  [EditorBrowsable(EditorBrowsableState.Never)]
  void IComponentConnector.Connect(int connectionId, object target)
  {
    switch (connectionId)
    {
      case 1:
        this.jointsGrid = (Grid) target;
        this.jointsGrid.MouseMove += new System.Windows.Input.MouseEventHandler(this.jointsGrid_MouseMove);
        this.jointsGrid.MouseLeave += new System.Windows.Input.MouseEventHandler(this.jointsGrid_MouseLeave);
        break;
      case 2:
        this.Joint = (ColumnDefinition) target;
        break;
      case 3:
        this.SteeringPoses = (ColumnDefinition) target;
        break;
      case 4:
        this.Value = (ColumnDefinition) target;
        break;
      case 5:
        this.Percentage = (ColumnDefinition) target;
        break;
      case 6:
        this.LowerLimit = (ColumnDefinition) target;
        break;
      case 7:
        this.UpperLimit = (ColumnDefinition) target;
        break;
      case 8:
        this.btnLowLimit_img = (System.Windows.Controls.Image) target;
        break;
      case 9:
        this.btnUpLimit_img = (System.Windows.Controls.Image) target;
        break;
      case 10:
        this.tooltip = (Popup) target;
        break;
      case 11:
        this.tooltipTextBlock = (TextBlock) target;
        break;
      default:
        this._contentLoaded = true;
        break;
    }
  }
}
